package com.mo.common.lucene.utils;

import java.io.IOException;
import java.io.StringReader;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.mo.common.lucene.interfaceAction.LuceneReader;

/**
 * 描述: Lucene工具类
 *
 * @author: yanpenglei
 * @create: 2017/11/7 17:47
 */
public class LuceneUtils {
	/**
     * 执行查询，并打印查询到的记录数
     *
     * @param query
     * @throws IOException
     */
    public static <T> T executeQuery(IndexReader indexReader,LuceneReader<T> reader,Query query) throws Exception {
//    	IndexReader indexReader = this.luceneClient.getIndexReader();
    	//创建一个索引的查找器，来检索索引库
        IndexSearcher   indexSearcher = new IndexSearcher(indexReader);
		TopDocs topDocs = indexSearcher.search(query, Integer.MAX_VALUE);
		 //打印查询到的记录数
        System.out.println("总共查询到" + topDocs.totalHits + "个文档");
    	T result = reader.read(indexSearcher,topDocs );
    	 if (indexReader != null) {
             indexReader.close();
         }
    	return result;
    }
    public static <T> T executeQueryPage(IndexReader indexReader,LuceneReader<T> reader,Query query
    		,Page page) throws Exception {
//    	IndexReader indexReader = this.luceneClient.getIndexReader();
    	//创建一个索引的查找器，来检索索引库
        IndexSearcher   indexSearcher = new IndexSearcher(indexReader);
        
        int totalRecord =  searchTotalRecord(indexSearcher,query);
	    //设置总记录数
	    page.setTotalRecord(totalRecord);
        ScoreDoc scoreDoc = getLastScoreDoc(page.getCurrentPage(), page.getPageSize(), query, indexSearcher);
        page.setAfterDoc(scoreDoc);
        int num = page.getPageSize()*(page.getCurrentPage()-1);//获取上一页的最后数量  
        page.setAfterDocId(num);
        TopDocs topDocs = indexSearcher.searchAfter(page.getAfterDoc(),query, page.getPageSize());
// 	   TopDocs topDocs = indexSearcher.search(query, 100);
		 //打印查询到的记录数
        System.out.println("总共查询到" + topDocs.totalHits + "个文档");
        
//        page.setAfterDoc(scoreDoc);
//        page.setAfterDocId(page.getCurrentPage()*page.getPageSize());
    	T result = reader.read(indexSearcher,topDocs );
    	 if (indexReader != null) {
             indexReader.close();
         }
    	return result;
    }
    /**
	   * @Title: searchTotalRecord
	   * @Description: 获取符合条件的总记录数
	   * @param query
	   * @return
	   * @throws IOException
	   */
	  public static int searchTotalRecord(IndexSearcher search,Query query) {
	    ScoreDoc[] docs = null;
	    try {
	      TopDocs topDocs = search.search(query, Integer.MAX_VALUE);
	      if(topDocs == null || topDocs.scoreDocs == null || topDocs.scoreDocs.length == 0) {
	        return 0;
	      }
	      docs = topDocs.scoreDocs;
	    } catch (IOException e) {
	      e.printStackTrace();
	    }
	    return docs.length;
	  }
	  private static ScoreDoc getLastScoreDoc(
			  int pageIndex,int pageSize,Query query
			  ,IndexSearcher searcher) throws IOException {  
	    if(pageIndex==1)return null;//如果是第一页就返回空  
	    int num = pageSize*(pageIndex-1);//获取上一页的最后数量  
	    TopDocs tds = searcher.search(query, num);  
	    return tds.scoreDocs[num-1];  
	} 
	 /**
     * 高亮处理
     *
     * @throws IOException
     */
	public static String HighlighterContent(String searchField , String content,String userInputText) throws Exception{
		Analyzer analyzer = new IKAnalyzer();//中文分词
		 //指定搜索字段和分析器
        QueryParser parser = new QueryParser(searchField, analyzer);
		//用户输入内容
        Query query = parser.parse(userInputText);
		// 关键字高亮显示的html标签，需要导入lucene-highlighter-xxx.jar
        SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter("<span style='color:red'>", "</span>");
        Highlighter highlighter = new Highlighter(simpleHTMLFormatter, new QueryScorer(query));
     // 内容增加高亮显示
        TokenStream tokenStream = analyzer.tokenStream("content", new StringReader(content));
        String contentHighlighter = highlighter.getBestFragment(tokenStream, content);
        
        System.out.println(contentHighlighter);
        return contentHighlighter;
	}
}